﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.Skins;
using DevExpress.LookAndFeel;
using DevExpress.UserSkins;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraBars.Helpers;
using AliboboStockLib.fetcher;
using AliboboStockLib.stockupdater.sbdetail;
using AliboboStockLib.date;
using System.IO;



namespace StockDetailsApp
{
    public partial class Form1 : RibbonForm
    {
        public Form1()
        {
            InitializeComponent();
            InitSkinGallery();

        }
        void InitSkinGallery()
        {
            SkinHelper.InitSkinGallery(rgbiSkins, true);
        }

        private void navBarControl_Click(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            StockSBIE.StockDataManager manager = new StockSBIE.StockDataManager();
        }

        private void tseDailyNavBarItem1_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            tabControl1.SelectedIndex = 0;
        }

        List<SBRecordState> SBTasks = null;
        private void bshtmNavBarItem2_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            tabControl1.SelectedIndex = 1;
            DateTime d = TseDailyIndexUpdater.getMaxTradeDate();

            TseSBDetailUpdater updater = new TseSBDetailUpdater();
               SBTasks = updater.getCurrentSBStates(d);
            sbTaskGridControl1.DataSource = SBTasks;

        }

        private void button1_Click(object sender, EventArgs e)
        {
            DateTime d = dateTimePicker1.Value;
            performTseDailyPrice(d,true);
            /*
            DateTime sd = DateTime.Parse("2012/05/31");
            DateTime ed = DateTime.Parse("2012/07/02");
            while (sd.CompareTo(ed) <= 0)
            {
                
                sd = sd.AddDays(1);
            }*/
        }

        private void performTseDailyPrice( DateTime d,bool force)
        {
            d = DateUtils.getValidTradeDate(d);
            DateTime realDate;
            try
            {
                List<List<String>> datas = TseDailyIndexFetcher.Fetch(d, out realDate, null);
                int c = TseDailyIndexUpdater.getCountOnDate(realDate);
                if (c > 0)
                {
                    if (force == false)
                    {
                        DialogResult r = MessageBox.Show("是否覆寫?", "當日已有資料:" + c + "筆", MessageBoxButtons.OKCancel);
                        if (r.Equals(DialogResult.OK) == false)
                            return;
                    }
                }
                if (datas == null)
                {
                    MessageBox.Show("無有效資料");
                    return;
                }
                TseDailyIndexUpdater.updateStockDaily(realDate, datas, "tse", null);
            }
            catch (Exception ee)
            {
                System.Diagnostics.Debug.WriteLine(ee.Message);
            }
        }

        private void startButton_Click(object sender, EventArgs e)
        {
            startButton.Checked = true;
            stopButton.Checked = false;
            processSB();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            /*
            int i = sbDetailManager.setErrorTaskToProcessWaiting();
            MessageBox.Show("總共重設:" + i + "筆");
            DateTime d = StockDataManager.getMaxTradeDate();
            SBTasks = sbDetailManager.getCurrentSBStates(d);
            dataGridView1.DataSource = SBTasks;
            */
        }
        protected void processSB()
        {

            DateTime d = TseDailyIndexUpdater.getMaxTradeDate();
            Tse_SB_Fetcher tseSBFetcher = new Tse_SB_Fetcher();
            DateTime vd = d.AddHours(16);

            TseSBDetailUpdater updater = new TseSBDetailUpdater();
            TimeSpan ts = DateTime.Now.Subtract(vd);
            if (ts.TotalSeconds < 0)
            {
                MessageBox.Show("還沒到下午四點,無法處理");
                return;
            }


            if (SBTasks == null)
                return;


            String ds = DateUtils.getPlanString(d);
            String path = "d:\\SBdata\\" + ds + "\\";
            Directory.CreateDirectory(path);



            foreach (SBRecordState sbTask in SBTasks)
            {
                if (sbTask.處理進度.Equals(SBTaskState.抓取中)||
                    sbTask.處理進度.Equals(SBTaskState.錯誤))
                {
                    //先回復
                    sbTask.處理進度 = SBTaskState.待處理;
                    updater.updateTaskState(sbTask.taskId, sbTask.處理進度, DateTime.Now);
                }
            }

            DateTime preD = DateTime.Now;
            
            foreach (SBRecordState sbTask in SBTasks)
            {
                if (sbTask.成交股數 == 0)
                    sbTask.處理進度 = SBTaskState.無資料;


                if (sbTask.處理進度.Equals(SBTaskState.待處理))
                {
                    sbTask.處理進度 = SBTaskState.抓取中;
                    try
                    {
                        //先看看有沒有這個檔案
                        String fileName = path + sbTask.代號 + "_" + sbTask.taskId.ToString("B") + ".sb";
                        if (File.Exists(fileName))
                        {
                            sbTask.處理進度 = SBTaskState.已抓取;
                        }
                        else
                        {
                            SBRecords records = tseSBFetcher.CrawlingSB(sbTask.代號, d, sbTask.交易筆數);
                            if (records != null)
                            {
                                records.SaveToFile(fileName);
                                sbTask.處理進度 = SBTaskState.已抓取;
                            }
                            else
                            {
                                sbTask.處理進度 = SBTaskState.錯誤;
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        System.Diagnostics.Debug.WriteLine(e.Message);
                        sbTask.處理進度 = SBTaskState.錯誤;
                    }
                    sbTask.處理時間 = DateUtils.getYYYYMMDDHHSS(DateTime.Now);
                    updater.updateTaskState(sbTask.taskId, sbTask.處理進度, DateTime.Now);
                }
                if (DateTime.Now.Subtract(preD).TotalSeconds > 1)
                {
                    sbTaskGridControl1.Refresh();
                    Application.DoEvents();
                    preD = DateTime.Now;
                }
            }
            //處理紀錄 
            int total = SBTasks.Count;
            int processed = 0;
            foreach (SBRecordState sbTask in SBTasks)
            {
                if (sbTask.處理進度.Equals(SBTaskState.完成))
                {
                    processed++;
                    continue;
                }
                if (sbTask.處理進度.Equals(SBTaskState.已抓取) == false)
                    continue;
                

                String fileName = path + sbTask.代號 + "_" + sbTask.taskId.ToString("B") + ".sb";
                SBRecords records = null;
                siInfo.Caption = "進度:" + processed + "/ " + total + " 目前:(" + sbTask.代號 + ")";
                try
                {
                    records = SBRecords.LoadFromFile(fileName);



                    updater.updateSBDetails(records.SBEntries, sbTask.taskId, sbTask.代號, d);
                    sbTask.處理進度 = SBTaskState.完成;
                    updater.updateTaskState(sbTask.taskId, sbTask.處理進度, DateTime.Now);
                    processed++;
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine(e.Message);
                    sbTask.處理進度 = SBTaskState.錯誤;
                    updater.updateTaskState(sbTask.taskId, sbTask.處理進度, DateTime.Now);
                }
                sbTask.處理時間 = DateUtils.getYYYYMMDDHHSS(DateTime.Now);
                if (DateTime.Now.Subtract(preD).TotalSeconds > 1)
                {
                    sbTaskGridControl1.Refresh();
                    Application.DoEvents();
                    preD = DateTime.Now;
                    siInfo.Caption = "進度:"+processed+"/ "+total+" 目前:(" + sbTask.代號+")";
                }

            }




        }
    }
}